package team.shixi.houtai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import team.shixi.houtai.common.Result;
import team.shixi.houtai.common.ResultUtil;
import team.shixi.houtai.entity.Admin;
import team.shixi.houtai.entity.User;
import team.shixi.houtai.service.UserService;


@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping//新增数据
    public Result<?> save(@RequestBody User user){

//        if (user.getName() != null && user.getIdcard() != null){
            //查询用户是否存在
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername,user.getUsername()).or().eq(User::getIdcard,user.getIdcard());
            User one = userService.getOne(queryWrapper);
            if (one != null){
                //如果存在则直接返回失败
                return Result.error("该身份信息已存在！");
            }
//        }


        user.setStatus(1);
        userService.save(user);

        return Result.success();
    }
    @PutMapping//更新数据
    public Result<?> update(@RequestBody User user){
        //查询用户是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getName,user.getName());
        User one = userService.getOne(queryWrapper);
        if (one != null){
            //如果存在则直接返回失败
            return Result.error("该信息已被实名!");
        }
        userService.updateById(user);
        return Result.success();
    }
    @PutMapping("/{id}")//冻结用户
    public Result<?> freeze(@PathVariable Long id){
        User user = userService.getById(id);
        if (user.getStatus() == 1){
            user.setStatus(0);
        }else {
            user.setStatus(1);
        }
        userService.updateById(user);
        return Result.success();
    }
    @DeleteMapping("/{id}")//删除数据
    public Result<?> delete(@PathVariable Long id){
        userService.removeById(id);
        return Result.success();
    }
    @GetMapping//查询数据
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){

        Page<User> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like((StringUtils.isNotBlank(search)),User::getName,search).or().
                eq((StringUtils.isNotBlank(search)),User::getIdcard,search);
        Page<User> userPage = userService.page(page, queryWrapper);
        return ResultUtil.success(userPage);
    }
}
